package com.wqz.tacos.impl;

import com.wqz.tacos.data.IngredientRepository;

import com.wqz.tacos.models.Ingredient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import lombok.extern.slf4j.Slf4j;

import java.sql.ResultSet;
import java.sql.SQLException;

// 写完实现后需要注入到对应的Controller中
@Slf4j
@Repository
public class JdbcIngredientRepository implements IngredientRepository {
    private JdbcTemplate jdbc;

    @Autowired
    public  JdbcIngredientRepository(JdbcTemplate jdbc){
        this.jdbc = jdbc;
    }

    @Override
    public Iterable<Ingredient> findAll() {
        return jdbc.query("select id, name, type from Ingredient", this::mapRowToIngredient);
    }

    @Override
    public Ingredient findOne(String id) {
        log.info("execute find one select sql--->");
        return jdbc.queryForObject("select id, name, type from Ingredient where id = ?", this::mapRowToIngredient, id);
    }

    @Override
    public Ingredient save(Ingredient ingredient) {
        // save Ingredient data
        log.info("save ingredient %s to the database", ingredient.toString());
        jdbc.update("insert into Ingredient(id,name, type) values (?,?,?)", ingredient.getId(),ingredient.getName(), ingredient.getType().toString());
        return ingredient;
    }

    // 将SQL语句结果集中的每行数据映射成一个对象
    private Ingredient mapRowToIngredient(ResultSet rs, int rowNum) throws SQLException {
        log.info("execute RowMapper sql");
        return new Ingredient(rs.getString("id"), rs.getString("name"), Ingredient.Type.valueOf(rs.getString("type")));
    }
}
